<?php

/**
 * 参考文献：https://www.cnblogs.com/reader/p/11593974.html
 */

namespace common\libraries;


class CurlLoginDemo{
    public $config = [
        //登录接口和参数
        'login_url' => 'http://localhost/login',
        'login_post_data' => [
            'username' => 'aaa',
            'password' => 'aaa',
        ],

        //数据接口
        'list_url' => 'http://localhost/list',
        'list_post_data' => [
            'page' => 1,
            'rows' => 30,
        ],
    ];

    public $cookie = '';

    //登录接口，获取cookie
    public function login()
    {
        $re = $this->post_curl($this->config['login_url'], $this->config['login_post_data'], 1);

        // 解析HTTP数据流
        list($header, $body) = explode("\r\n\r\n", $re);
        // 解析COOKIE
        preg_match("/set\-cookie:([^\r\n]*)/i", $header, $matches);
        //请求的时候headers 带上cookie就可以了
        $cookie = explode(';', $matches[1])[0];

        $this->cookie = trim($cookie);
    }

     //执行登录后的操作
     public function execute()
     {
         $re = $this->post_curl($this->config['list_url'], $this->config['list_post_data']);

         //$json = json_decode($re, true);

         var_dump($re);
     }

     //发送请求
     function post_curl($url, $params=[], $isShowHeader=0){
         $httpInfo = array();
         $ch = curl_init();

         curl_setopt( $ch, CURLOPT_HEADER, $isShowHeader);
         curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
         curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36' );
         curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
         curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
         curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );

         curl_setopt( $ch , CURLOPT_POST , true );
         curl_setopt( $ch , CURLOPT_POSTFIELDS , http_build_query($params));
         curl_setopt( $ch , CURLOPT_URL , $url );

         if($this->cookie){
             curl_setopt($ch, CURLOPT_COOKIE, $this->cookie);//设置cookie
         }

         $response = curl_exec( $ch );
         if ($response === FALSE) {
           return false;
         }

         curl_close( $ch );
         return $response;
     }

     //启动
     public function start()
     {
         try{
             $this->login();
             if(!$this->cookie){
                throw new \Exception("登录失败！");
             }
             $this->execute();
         }catch(\Exception $e){
             print($e);
         }
     }

 }

/**
 *
 *
 * $obj = new CurlLoginDemo();
 * $obj->start();
 *
 *
 *
 */
